import { defineStore } from 'pinia';
import { ref, onMounted } from 'vue';
import request from '@/utils/request';
import { showNotification } from '@/utils/notify';

type RoleMenu = {
  id: number; // 假设后台返回的记录有唯一标识
  roleCode: string;
  menuId: string;
}


type RoleMenuPage = {
  code: number;
  message: string;
  data: {
    records: RoleMenu[]; // 假设后台返回的记录数组
    total: number; // 总记录数
    size: number; // 每页显示的记录数
  }; 
}

export const useRoleMenuStore = defineStore('role-menu', () => {
  const roleMenus = ref<RoleMenu[]>([]);
  const total = ref(0); // 总记录数
  const currentPage = ref(1); // 当前页码
  const pageSize = ref(10); // 每页显示数量

  const fetchRoleMenus = async () => {
    try {
      const { data } = await request.get<RoleMenuPage>(`api/sys-menu/page?current=${currentPage.value}&size=${pageSize.value}`);
      roleMenus.value = data.records;
      total.value = data.total;
    } catch (error) {
      showNotification("获取角色菜单列表失败", true);
    }
  };

  const addRoleMenu = async (roleMenu: RoleMenu) => {
    const { code, data } = await request.post<{ code: number; data: object }>('/api/role-menus/add', roleMenu);
    if (code === 200) {
      roleMenus.value.push(roleMenu);
      showNotification("角色菜单添加成功", false);
    } else {
      showNotification("角色菜单添加失败", true);
    }
  };

  const updateRoleMenu = async (index: number, updatedRoleMenu: RoleMenu) => {
    try {
      const { code, data } = await request.post<{ code: number; data: object }>('/api/role-menus/update', updatedRoleMenu);
      if (code === 200) {
        roleMenus.value[index] = updatedRoleMenu;
        showNotification("角色菜单更新成功", false);
      } else {
        showNotification("角色菜单更新失败", true);
      }
    } catch (error) {
      showNotification("角色菜单更新失败", true);
    }
  };

  const deleteRoleMenu = async (index: number) => {
    try {
      const roleMenuId = roleMenus.value[index].id;
      const { code, data } = await request.delete<{ code: number; data: object }>(`/api/role-menus/delete/${roleMenuId}`);
      if (code === 200) {
        roleMenus.value.splice(index, 1);
        showNotification("角色菜单删除成功", false);
      } else {
        showNotification("角色菜单删除失败", true);
      }
    } catch (error) {
      showNotification("角色菜单删除失败", true);
    }
  };

  const changePage = (page: number) => {
    currentPage.value = page;
    fetchRoleMenus();
  };

  onMounted(() => {
    fetchRoleMenus();
  });

  return {
    roleMenus,
    total,
    currentPage,
    pageSize,
    addRoleMenu,
    updateRoleMenu,
    deleteRoleMenu,
    fetchRoleMenus,
    changePage,
  };
});